import { any } from "../core/logic";
import { ComponentEvent } from "../event/ComponentEvent";
import { ParamManager } from "../gpu/ParamManager";
import { Register } from "../register/Register";
class Component extends ParamManager {
  constructor(opts = {}, share) {
    super(opts, share);
    this._type = any(opts.type, ComponentType.Component);
    this._enable = any(opts.enable, true);
    this._eids = new Set();
    this.event = new ComponentEvent(this.type);
    this.event.target = this;
  }
  active() {
    this._enable = true;
    this.update();
    return this;
  }
  deactive() {
    this._enable = false;
    this.update();
    return this;
  }
  get type() {
    return this._type;
  }
  set type(v) {
    this._type = v;
    return this;
  }
  get enable() {
    return this._enable;
  }
  get eids() {
    return this._eids;
  }
  attach(eid) {
    this.eids.add(eid);
    this.update();
  }
  detach(eid) {
    this.eids.delete(eid);
  }
  destroy() {
    if (this.eids.size <= 0) {
      //附加到了实体中，从实体以此删除
      this.removeAllParam();
      Register.instance.manager(this.type).remove(this.id); //组件管理中移除。
      this.publish(this.event);
      return true;
    }
    return false;
  }
  update(mode = "value") {
    if (!this.autoUpdate || !this.enable) {
      return false;
    }
    
    if (this.eids.size <= 0) {
      return false;
    }
    const groups = this.getGroup();
    if (groups.length <= 0) {
      return false;
    }
    this.updateState();
    if (this.getState()) {
      this.updateHash();
      this._onChangeCallback();
      this.event.mode = mode;
      this.publish(this.event);
      return true;
    }
    return false;
  }
  updateHash() {}
  updateState() {}
  getGroup() {
    let groups = [];
    this.eids.forEach(id => {
      const entity = Register.instance.entityManager.get(id);
      if (entity) {
        if (entity.type == "Group" || entity.type == "Scene") {
          groups.push(id);
        } else {
          let group = entity.getRoot().group;
          if (group!="default") {
            groups.push(group);
          }
        }
      }
    });
    return groups;
  }
  onChange(callback) {
    this._onChangeCallback = callback;
    return this;
  }
  _onChangeCallback() {}
}
const ComponentType = {
  Component: -1,
  Mesh: 0, //Mesh
  Trans: 1, //Trans
  TransInstance: 1,
  Pick: 2, //拾取
  Script: 3, //碰撞
  HemisLight: 4, //半球光
  EnviromentLight: 5, //IBL光
  AmbientLight: 6, //环境光
  PointLight: 7, //点光源
  DirectionLight: 8, //平行光
  SpotLight: 9, //聚光灯
  AreaLight: 10, //区域光
  Camera: 11, //相机，提供视图投影矩阵
  Background: 12,
  PunctualLight: 13, // 精准光源组件，由场景中所有的精准光源构成。
  MeshRender: 14, //三维渲染实体组件，由当前所有渲染实体进行渲染打包后的结果。
  Destroy: 15, //销毁组件。
  Animation: 16,
  Orbit: 17,
  PostProcessing: 18,
  Plot:19,
  Transform:20
};
export { Component, ComponentType };
